// pages/search/search.js
var app = getApp();
import api from '../../utils/api.js'
import { config } from '../../utils/config'
import { HTTP } from '../../utils/http.js'
let http = new HTTP()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        list: [], //菜谱和单品
        list1: [], //功能性专题
        show: false, //搜索无结果
        show1: true, //未输入搜索内容是显示
        show2: true, //历史搜索是否显示
        menuShow: true, // 已选菜单是否展示 
        hot: [],
        imgUrl: config.imgUrl,
        history: [], //历史搜索
        classify: 0, //区分搜索结果为菜谱还是单品 0单品 1菜谱
        goods: [], // 相关菜谱的列表
    },
    //新版搜索食材名提示框
    getProducts(obj) {
        return new Promise((resolve, reject) => {
            console.log('=========================')
            http.request({
                url: api.getProducts,
                data: obj,
                success: res => {
                    console.log(res)
                    if (res.msg == "没有找到相关商品以及菜谱") {
                        this.setData({
                            show: false,
                            show1: false,
                            list: [],
                            list1: [],
                            goods: []
                        })
                        return false
                    }
                    if (res.code == 202) {
                        console.log("菜谱")
                        this.setData({
                                show: false,
                                show1: false,
                                list: res.data,
                                list1: [],
                                goods: res.data,
                                key: obj.name,
                                classify: 1,
                            })
                            // resolve(res.data)
                    } else {
                        this.setData({
                            show: false,
                            show1: false,
                            list: res.data,
                            list1: res.data[0].pclas.projectstype,
                            key: obj.name,
                            classify: 0,
                        })
                        resolve(res.data)
                    }
                }
            })
        })
    },
    //通过食材获取相关所有相关菜谱接口
    getPidCookbooks(obj) {
        console.log(obj),
            http.request({
                url: api.getPidCookbookS,
                data: obj,
                success: res => {
                    var goods = []
                    console.log('goods', res)
                    if (res.code == 200) {
                        goods = res.data;
                        this.setData({
                            goods,
                            show: false
                        })
                    }
                }
            })
    },
    //获取热门的菜谱分类主题标签
    getCookbookProjects(obj) {
        http.request({
            url: api.getCookHotProjects,
            data: obj,
            success: res => {

                if (res.data) {
                    var hot = res.data
                    hot.length = 6
                    this.setData({
                        hot: res.data
                    })
                }
            }
        })
    },
    //输入展示
    write(e) {
        if (e.detail.value) {
            this.getProducts({ name: e.detail.value, }).then(res => {
                //拿到搜索结果
                //拿搜索结果的id去搜相关的菜谱
                console.log(11111111111111111111)
                console.log(res)
                this.getPidCookbooks({ id: res[0].id, page: 1, pagesize: 20 });
                // this.getPidCookbooks({ id:res[0].id, page: 1, pagesize: 50 }).then(res => {
                //     console.log(22222222222222);
                //     console.log(res)
                // })
                // var arr = []
                // res.map((item)=>{
                //   var id = item.id
                //   arr.push(this.getPidCookbooks({ id, page: 1, pagesize: 50 }).then(res=>{
                //     return res
                //   }))
                //   Promise.all(arr).then(res=>{
                //     console.log(res)
                //     var goods = []
                //     res.map((item)=>{
                //       goods=goods.concat(item)
                //     })
                //     console.log(goods)
                //     this.setData({
                //       goods,
                //       show:false
                //     })
                //   })
                // })


            })
        } else {
            this.setData({
                list1: [],
                list: [],
                goods: [],
                show1: true,
                show: false
            })
        }
    },
    //点击跳转商品专题页面
    toProject(e) {
        console.log("跳转功能性专题--" + this.data.list1[0].name)
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: "/pages/project/project?id=" + id
        })
    },
    hotSearch(e) {
        console.log(e.currentTarget.dataset.id)
        wx.navigateTo({
            url: "/pages/project/project?id=" + e.currentTarget.dataset.id
        })
    },
    //删除输入框的内容
    del() {
        this.setData({
            key: "",
            list: [],
            list1: [],
            show1: true,
            goods: [],
            show: false
        })
    },
    //删除历史搜索的内容
    delAll() {
        wx.setStorageSync("history-search", [])
        this.setData({
            history: [],
            show2: false,
        })
    },
    toVideo(e) {
        var id = e.target.dataset.id
        wx.navigateTo({
            url: "/pages/video/video?id=" + id
        })
    },
    count() {
        var newList = wx.getStorageSync("select-menus") || []
        newList.filter((item) => {
            return item.num
        })
        var count = 0
        newList.map((item) => {
            count += item.num
        })
        this.setData({
            num: count
        })
    },
    toMain(e) {
        if (this.data.num == 0) {
            wx.showToast({
                title: '您还未选菜',
                icon: "none"
            })
        } else {
            wx.navigateTo({
                url: "/pages/mainCourse/mainCourse"
            })
        }
    },
    // 点击添加菜谱
    add(e) {
        if (!app.globalData.has) {
            wx.showToast({
                title: '您附近暂时没有接入商家，不能加入菜单',
                icon: "none"
            })
            return false
        }
        var listMenus = wx.getStorageSync('select-menus') || [];
        for (let v of listMenus) {
            if (v.id == e.target.dataset.id) {
                wx.showToast({
                    title: '请不要重复添加',
                    icon: 'none',
                    duration: 1500
                })
                return false;
            }
        }

        listMenus.push({
            flag: true,
            id: e.target.dataset.id,
            name: e.target.dataset.name,
            main_img_url: e.target.dataset.img,
            ingredients: [],
            count: e.target.dataset.count,
            time: e.target.dataset.time,
            seasoning_count: e.target.dataset.seasoning_count,
            num: 1
        });
        wx.setStorageSync("select-menus", listMenus);
        wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1500
        })
        this.count()
    },
    //搜索
    search(e) {
        var id = e.target.dataset.id
        var classify = e.target.dataset.classify
        var name = e.target.dataset.name
        app.globalData.id = ""
        var history = wx.getStorageSync("history-search") || []
        var item = history.filter((item) => {
            return item.id == id
        })[0]
        if (this.data.classify == 1) { // 判断是否搜索结果为菜谱
            if (!item) {
                history.push({ id, name, classify: 1 })
                wx.setStorageSync("history-search", history)
            }
            wx.navigateTo({
                url: "/pages/video/video?id=" + id
            })
        } else { // 判断是否搜索结果为单品
            if (!item) {
                history.push({ id, name, classify: 0 })
                wx.setStorageSync("history-search", history)
            }
            wx.navigateTo({
                url: "/pages/detail/detail?id=" + id
            })
        }
    },
    //点击搜索
    clickSearch(e) {
        var id = e.target.dataset.id
        var classify = e.target.dataset.classify
        var name = e.target.dataset.name

        app.globalData.id = ""
        var history = wx.getStorageSync("history-search") || []
        var item = history.filter((item) => {
                return item.id == id
            })[0]
            // this.search(id, classify,name)
        if (classify == 1) { // 判断是否搜索结果为菜谱
            if (!item) {
                history.push({ id, name, classify: 1 })
                wx.setStorageSync("history-search", history)
            }
            wx.navigateTo({
                url: "/pages/video/video?id=" + id
            })
        } else { // 判断是否搜索结果为单品
            if (!item) {
                history.push({ id, name, classify: 0 })
                wx.setStorageSync("history-search", history)
            }
            wx.navigateTo({
                url: "/pages/detail/detail?id=" + id
            })
        }
    },
    //键盘点击确定
    searchBtn() {
        if (this.data.list1.length != 0) {
            console.log("跳转功能性专题--" + this.data.list1[0].name)
            const id = this.data.list1[0].id
            wx.navigateTo({
                url: "/pages/project/project?id=" + id
            })
        } else if (this.data.list.length != 0) {
            var id = this.data.list[0].id
            var name = this.data.list[0].name
            this.search(id, -1, name)
        } else {
            this.setData({
                show: true
            })
        }
        console.log(this.data.goods)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.count()
        this.getCookbookProjects()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.del()
        var history = wx.getStorageSync("history-search") || []
        history.reverse()
        if (history.length == 0) {
            this.setData({
                history: [],
                show2: false,
            })
        } else {
            this.setData({
                history,
                show2: true,
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    }
})